<template>
  <div class="case-form-page">
    <div class="form-card">
      <h2 class="form-title">案件信息录入</h2>
      <el-form
        ref="caseForm"
        :model="formData"
        label-width="100px"
        class="case-form"
        :rules="formRules"
      >
        <!-- 原告 -->
        <el-form-item label="原告" prop="plaintiff">
          <el-input
            v-model="formData.plaintiff"
            placeholder="请输入原告信息"
            @input="updateCaseTitle"
          />
        </el-form-item>

        <!-- 被告 -->
        <el-form-item label="被告" prop="defendant">
          <el-input
            v-model="formData.defendant"
            placeholder="请输入被告信息"
            @input="updateCaseTitle"
          />
        </el-form-item>

        <!-- 案件类型 -->
        <el-form-item label="案件类型" prop="caseType">
          <el-select v-model="formData.caseType" placeholder="请选择案件类型">
            <el-option
              v-for="item in caseTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <!-- 案件标题（自动生成） -->
        <el-form-item label="案件标题" prop="caseTitle">
          <el-input
            v-model="formData.caseTitle"
            placeholder="自动生成案件标题"
            readonly
          />
        </el-form-item>

        <!-- 案件描述 -->
        <el-form-item label="案件描述" prop="description">
          <el-input
            v-model="formData.description"
            placeholder="请详细描述案件经过..."
            type="textarea"
            :rows="6"
          />
        </el-form-item>

           <div class="material-header">
            <el-button
              type="primary"
              size="small"
              icon="Plus"
              @click="addMaterial"
              style="margin-bottom: 10px;"
            >
              添加材料
            </el-button>

            <p class="sub-title">已添加 {{ formData.materials.length }} 项材料</p>
          </div>
        <!-- 案件材料上传区域 -->
        <el-form-item label="案件材料" class="material-section">
       
          <!-- 材料项列表 -->
          <div
            v-for="(material, index) in formData.materials"
            :key="index"
            class="material-item"
          >
            <!-- 材料类型选择 + 删除按钮 -->
            <div class="material-top">
              <el-select
                v-model="material.type"
                placeholder="选择材料类型"
                class="type-select"
              >
                <el-option label="身份证" value="ID_CARD"></el-option>
                <el-option label="起诉状" value="COMPLAINT"></el-option>
                <el-option label="视频" value="VIDEO"></el-option>
                <el-option label="图片" value="IMAGE"></el-option>
                <el-option label="其他" value="OTHER"></el-option>
              </el-select>

              <el-button
                type="danger"
                icon="Delete"
                size="mini"
                @click="removeMaterial(index)"
              ></el-button>
            </div>

                <!-- 上传区域（截图样式） -->
            <div class="upload-box">
              <div class="upload-icon">
                <i class="el-icon-upload-cloud"></i>
              </div>
              
              <!-- 如果已上传文件，显示URL -->
              <div v-if="material.url" class="upload-success">
                <p class="upload-tip success">✓ 文件上传成功!</p>
                <p class="file-url">{{ material.url }}</p>
                <el-button type="success" size="mini" @click="chooseFile(index)">
                  重新上传
                </el-button>
              </div>
              
              <!-- 未上传文件时显示 -->
              <div v-else>
                <p class="upload-tip">拖放文件到此处或点击上传</p>
                <p class="format-tip">
                  支持格式：PDF, DOC, JPG, PNG, MP4等（单个文件不超过20MB）
                </p>
                <el-button type="primary" size="mini" @click="chooseFile(index)">
                  选择文件
                </el-button>
              </div>
              
              <!-- 隐藏实际上传控件 -->
              <input
                type="file"
                class="hidden-upload"
                :id="`upload-${index}`"
                @change="handleFileChange($event, index)"
              />
            </div>
          </div>
        </el-form-item>


        <!-- 操作按钮 -->
        <div class="form-actions">
          <el-button type="default" @click="saveDraft">保存草稿</el-button>
          <el-button type="primary" @click="submitForm">提交</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { ElMessage, ElMessageBox, ElLoading } from "element-plus";
import { useRouter } from "vue-router";
import { applyCaseApi } from "../../api/applyCase";


const router = useRouter();

// 表单数据
const formData = reactive({
  plaintiff: "",
  defendant: "",
  caseType: "",
  caseTitle: "",
  description: "",
  caseId: "",
  operation: "",
  materials: [
    {
      type: "",
      url: ""
    },
  ],
});

// 案件类型选项
const caseTypeOptions = ref([
  { label: "民事案件", value: "CIVIL" },
  { label: "刑事案件", value: "CRIMINAL" },
  { label: "行政案件", value: "ADMINSTRATIVE" },
  { label: "其他案件", value: "OTHER" },
]);

// 表单验证规则
const formRules = reactive({
  plaintiff: [
    { required: true, message: "请输入原告信息", trigger: "blur" },
  ],
  defendant: [
    { required: true, message: "请输入被告信息", trigger: "blur" },
  ],
  caseType: [
    { required: true, message: "请选择案件类型", trigger: "change" },
  ],
  description: [
    { required: true, message: "请描述案件经过", trigger: "blur" },
    { min: 10, message: "描述至少10个字符", trigger: "blur" },
  ],
});

// 更新案件标题
const updateCaseTitle = () => {
  if (formData.plaintiff && formData.defendant) {
    formData.caseTitle = `${formData.plaintiff}诉${formData.defendant}一案`;
  } else {
    formData.caseTitle = "";
  }
};

// 添加材料项
const addMaterial = () => {
  formData.materials.push({
    type: "",
    url: "",
  });
};

// 移除材料项
const removeMaterial = (index) => {
  ElMessageBox.confirm(
    "确定要移除该材料吗？",
    "确认移除",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(() => {
    formData.materials.splice(index, 1);
    ElMessage.success("材料已移除");
  });
};

// 触发文件选择
const chooseFile = (index) => {
  document.getElementById(`upload-${index}`).click();
};

// 处理文件选择
const handleFileChange = async (e, index) => {
  const file = e.target.files[0];
  if (!file) return;

  // 校验文件大小
  if (file.size / 1024 / 1024 > 20) {
    ElMessage.error("文件大小不能超过20MB");
    e.target.value = ""; // 清空已选文件
    return;
  }

  // 校验文件格式（简单示例，可扩展）
  const validFormats = ["pdf", "doc", "jpg", "png", "mp4"];
  const fileFormat = file.name.split(".").pop().toLowerCase();
  if (!validFormats.includes(fileFormat)) {
    ElMessage.error("不支持的文件格式");
    e.target.value = "";
    return;
  }

   // 显示上传loading
    const loading = ElLoading.service({ text: "文件上传中..." });
  try {
    
    // 创建FormData并上传文件
    const uploadFormData = new FormData();
    uploadFormData.append("file", file);
    
     // 调用API上传文件 - 使用await等待异步响应
    const res = await applyCaseApi.uploadFile(uploadFormData);
    
    // 将后端返回的URL（在message字段中）赋值给对应材料项的url字段
    formData.materials[index].url = res.message;
    
    ElMessage.success("文件上传成功");
    e.target.value = ""; // 重置上传控件
    loading.close();
  } catch (error) {
    console.error("文件上传失败:", error);
    ElMessage.error("文件上传失败，请稍后重试");
    e.target.value = ""; // 清空已选文件
     loading.close(); 
  }
};

// 保存草稿（模拟）
const saveDraft = async () => {
  if (!formData.plaintiff || !formData.defendant) {
    ElMessage.warning("请至少填写原告和被告信息");
    return;
  }
  try {
    const loading = ElLoading.service({ text: "保存中..." });
    formData.operation='DRAFT';
    await applyCaseApi.applyCase(formData);
    ElMessage.success("草稿保存成功");
    loading.close();
  } catch (error) {
    ElMessage.error("保存草稿失败");
  }
};

// 提交表单（模拟）
const submitForm = async () => {
  const hasInvalid = formData.materials.some(
    (item) => !item.type || !item.url
  );

  if (hasInvalid) {
    ElMessage.warning("请完善所有材料的类型和文件上传");
    return;
  }
  const loading = ElLoading.service({ text: "提交中..." });
  try {
    formData.operation='SUBMIT';
    await applyCaseApi.applyCase(formData);
    ElMessage.success("案件提交成功");
  } catch (error) {
    ElMessage.error("提交失败，请稍后重试");
  }
  loading.close();
};


//文件上传
const uploadFile = async (file) => { 
   const loading = ElLoading.service({ text: "上传中..." });
  try {
    const formData = new FormData();
    formData.append("file", file);
    const res = await applyCaseApi.uploadFile(formData);
    ElMessage.success("上传成功");
    loading.close();
    return res.data;
  } catch (error) {
    ElMessage.error("上传失败，请稍后重试");
    loading.close();
  }
};
</script>

<style scoped>
/* 页面基础布局 */
.case-form-page {
  display: flex;
  justify-content: center;
  padding: 24px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.form-card {
  width: 100%;
  max-width: 800px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  padding: 30px;
}

.form-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin-bottom: 24px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f2f3f5;
}

/* 案件材料区域 */
.material-section {
  margin-top: 20px;
}

.material-header {
  display: flex;
  margin-bottom: 16px;
}

.material-desc {
  display: block !important;
  flex-direction: column;
}

.main-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.sub-title {
  font-size: 14px;
  color: #999;
  margin: 4px 0 0;
  margin-left: 10px;
}

/* 单个材料项 */
.material-item {
  background: #f9fafb;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.material-top {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.type-select {
  width: 60%;
  min-width: 140px;
  font-size: 14px;
}

/* 上传区域样式（截图还原） */
.upload-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  padding: 24px;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  background: #fdfdfd;
  cursor: pointer;
}

.upload-icon {
  font-size: 40px;
  color: #c0c4cc;
  margin-bottom: 12px;
}

.upload-tip {
  font-size: 14px;
  color: #666;
  margin: 0 0 4px;
}

.format-tip {
  font-size: 12px;
  color: #999;
  margin: 0;
}

.hidden-upload {
  display: none;
}

/* 操作按钮 */
.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .type-select {
    width: 100%;
  }
}
</style>